<template>
  <a-spin :spinning="loading">
    <div class="modal-header">
      <div class="modal-title">
        <medicine-box-outlined />
        <span v-if="id">{{ l('EditRole') }}:{{ displayName }}</span>
        <span v-if="!id">{{ l('CreateNewRole') }}</span>
      </div>
    </div>
    <div class="modal-body">
      <!-- 提示 -->
      <a-alert :message="l('Note_RefreshPageForPermissionChanges')" type="info" closable showIcon />
      <!-- tab切换 -->
      <a-tabs defaultActiveKey="1">
        <!-- 角色名称 -->
        <a-tab-pane key="1" tab="角色">
          <a-form :model="form" layout="vertical" @submit="handleSubmit" ref="formRef">
            <a-form-item
              :label="l('RoleName')"
              name="displayName"
              :rules="[
                { required: true, message: l('ThisFieldIsRequired'), trriger: 'blur' },
                { message: l('MaxLength'), max: 64, trriger: 'blur' },
              ]"
            >
              <a-input :placeholder="l('RoleName')" v-model:value="form.displayName" />
            </a-form-item>
            <a-form-item :label="l('Default')">
              <a-switch
                checkedChildren="开"
                unCheckedChildren="关"
                v-model:checked="form.isDefault"
              />
            </a-form-item>
            <!-- <a-form-item>
                        <span slot="label">
                            {{ l('Default') }}&nbsp;
                            <a-tooltip :title="l('DefaultRole_Description')">
                                
                            </a-tooltip>
                        </span>
                        <a-switch  :checkedChildren="l('Yes')" :unCheckedChildren="l('No')" />
                    </a-form-item> -->
          </a-form>
        </a-tab-pane>
        <!-- 权限 -->
        <a-tab-pane key="2" tab="权限" class="Permissions" :forceRender="true">
          <span>
            <safety-certificate-outlined />
            {{ l('Permissions') }}
          </span>
          <p />
          <permission-tree
            ref="treeRef"
            :multiple="true"
            :dropDownStyle="{ 'max-height': '500px' }"
            :defaultSelectedPermissions="premissions"
            @selectedPermissionsChange="selectedPermissions = $event"
          >
          </permission-tree>
        </a-tab-pane>
      </a-tabs>
    </div>
    <!-- 按钮 -->
    <div class="modal-footer">
      <a-button :disabled="saving" @click="close()" type="button">
        <close-circle-outlined />
        {{ l('Cancel') }}
      </a-button>
      <a-button :loading="saving" :type="'primary'" @click="handleSubmit()">
        <save-outlined />
        {{ l('Save') }}
      </a-button>
    </div>
  </a-spin>
</template>

<script lang="ts">
  import { ModalComponentBase } from '/@/shared/component-base';
  import { RoleServiceProxy } from '/@/shared/service-proxies';
  import { PermissionTree } from '/@/app/admin-shared';
  import { defineComponent } from 'vue';
  import {
    CloseCircleOutlined,
    SafetyCertificateOutlined,
    SaveOutlined,
    MedicineBoxOutlined,
  } from '@ant-design/icons-vue';
  import { CreateOrUpdateRoleInput } from '/@/shared/service-proxies/service-proxies';

  export default defineComponent({
    name: 'create-or-edit-role',
    components: {
      CloseCircleOutlined,
      MedicineBoxOutlined,
      SafetyCertificateOutlined,
      SaveOutlined,
      PermissionTree,
    },
    mixins: [ModalComponentBase],
    props: {
      id: Number,
      displayName: String,
    },
    data() {
      const premissions: any = null;
      return {
        form: {
          displayName: '',
          isDefault: false,
        },
        // 选中的权限过滤
        selectedPermission: [],
        _roleServiceProxy: new RoleServiceProxy(),
        premissions: premissions,
        /** 角色选中的权限数据，提交时使用的 */
        selectedPermissions: [] as string[],
      };
    },
    mounted() {
      this.getData();
    },
    methods: {
      /**
       * 获取数据
       */
      getData() {
        this.loading = true;
        this._roleServiceProxy
          .getForEdit(this.id)
          .finally(() => {
            this.loading = false;
          })
          .then((result) => {
            this.premissions = result.grantedPermissionNames || [];
            this.selectedPermissions = this.premissions;
            this.form.displayName = result.role.displayName;
            this.form.isDefault = result.role.isDefault;
          });
      },
      /**
       * 提交表单
       */
      handleSubmit() {
        (this.$refs.formRef as any).validate().then(() => {
          let parmas = {
            role: {
              displayName: this.form.displayName,
              id: this.id,
              isDefault: this.form.isDefault ? this.form.isDefault : false,
            },
            grantedPermissionNames: this.selectedPermissions || [],
          };
          let roleinput: CreateOrUpdateRoleInput = new CreateOrUpdateRoleInput();
          roleinput.init(parmas);
          this.saving = true;
          this.loading = true;
          this._roleServiceProxy
            .createOrUpdate(roleinput)
            .finally(() => {
              this.saving = false;
              this.loading = false;
            })
            .then(() => {
              this.notify.success(this.l('SavedSuccessfully'));
              this.success(true);
            });
        });
      },
    },
  });
</script>

<style scoped lang="less">
  .modal-header {
    .anticon {
      margin-right: 10px;
    }
  }
  .Permissions {
    height: 50vh;
    overflow-y: auto;
  }
  .modal-body {
    overflow-y: hidden;
  }
</style>
